<script lang="ts" setup>
import {ElMessage} from "element-plus";
import {nextTick, onMounted, reactive, ref} from "vue";
import useSettingStore from '../../../store/modules/setting.ts';
import {reqAddOrUpdateRole, reqAllMenuList, reqAllRoleList, reqSetPermission} from "../../../api/acl/role";
import type {MenuData, RoleData} from "../../../api/acl/role/type.ts";

const settingStore = useSettingStore(); //获取仓库

let userInput = ref<string>('');//用户输入
let currentPage = ref<number>(1); //当前页
let pageSize = ref<number>(10) //页面记录数
let total = ref<number>(0); //总记录数

let newRole = ref<RoleData>({
  roleName: ''
});//新增职位

let isShow = ref<boolean>(false);//dialog是否出现

let roleForm = ref();//表单组件对象

const menuList = ref<MenuData[]>([]); //树型复选框出现与否

const defaultProps = {
  children: 'children',
  label: 'name',
};//树状图的对应规则

let isShowDrawer = ref<boolean>(false);//权限抽屉出现与否

const menuParams = ref<number[]>([]);//收集menu的pid

const tree = ref(); //树型控件的对象

//存储所有角色的集合
const roleList = reactive<RoleData[]>([]);

//分页请求
const reqPage = async (page = 1) => {
  currentPage.value = page;
  try {
    const result = await reqAllRoleList(currentPage.value, pageSize.value, userInput.value);
    if (result.code === 200) {
      roleList.length = 0;//清空数据，reactive只能这样清
      total.value = result.data.total;
      Object.assign(roleList, result.data.records);
    }
  } catch (e) {
    ElMessage({type: "error", message: "角色管理页面，分页查询方法出错了"});
  }
}

//挂载时请求一下数据
onMounted(async () => {
  await reqPage();
})

//模糊查询
const searchCareer = async () => {
  try {
    await reqPage();
  } catch (e) {
    ElMessage({type: "error", message: "角色管理页面，模糊查询方法出错了"});
  }
}

//重置
const resetPage = () => {
  settingStore.refresh = !settingStore.refresh;
}

//递归获取所有select字段为真的id
const getRolePerssion = (allData: MenuData[], initArr: number[]) => {
 allData.forEach((item: MenuData) => {
   if (item && (!item.children || item.children.length === 0)) {
     item.select && initArr.push(item.id as number);
   } else if (item.children && item.children.length > 0) {
     getRolePerssion(item.children, initArr);
   }
  });
 return initArr;
}

//分配权限
const assignRole = async (role: any) => {
  newRole.value = role;
  menuParams.value = [];
  try {
    let result = await reqAllMenuList(role.id);
    menuList.value = result.data;
    menuParams.value = getRolePerssion(menuList.value, []);
  } catch (e) {
    ElMessage({type: "error", message: "分配权限出错了"})
  }
  isShowDrawer.value = true;
}
//编辑职业
const editCareer = (role: any) => {
  newRole.value = role;//给表单赋值
  isShow.value = true;
  //清空校验
  nextTick(() => {
    roleForm.value.clearValidate("newRole");
  });
}
//删除职业
const deleteCareer = (role: any) => {

}

//新增职位
const addRole = () => {
  //清空数据
  newRole.value = {roleName: ''}
  isShow.value = true;
  //清空校验
  nextTick(() => {
    roleForm.value.clearValidate("newRole");
  });
}

//表单校验
const validatorRole = (rule: any, value: string, callback: any) => {
  if (value && value.length > 1) {
    callback();
  } else {
    callback(new Error("长度至少为2"))
  }
}
const rules = {
  roleName: [{required: true, trigger: "blur", validator: validatorRole}]
}

//保存用户数据
const saveRole = async () => {
  //校验表单
  try {
    await roleForm.value.validate();
    const result = await reqAddOrUpdateRole(newRole.value);
    if (result.code !== 200) return;
    ElMessage({type: "success", message: !!newRole.value.id ? '更新成功' : "保存成功"})
  } catch (e) {
    ElMessage({type: "warning", message: "表单校验有问题"});
  }
  isShow.value = false;
  //在分页查询属性页面
  await reqPage(!!newRole.value.id ? currentPage.value : 1);
}
//取消
const cancel = () => {
  isShow.value = false;
  isShowDrawer.value = false;
}

//分配权限
const assignPermission = async () => {
  try {
    const checkedKeys = tree.value.getCheckedKeys();
    console.log(newRole.value.id, checkedKeys)
    await reqSetPermission(newRole.value.id as number, checkedKeys);
    ElMessage({type: "success", message: "权限分配成功"});
  } catch (e) {
    ElMessage({type: "error", message: "权限分配失败"});
  }
  isShowDrawer.value = false;
}


//
</script>

<template>
  <el-card>
    <el-form class="container" inline>
      <el-form-item label="角色名称">
        <el-input v-model.trim="userInput" placeholder="输入角色"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchCareer">搜索</el-button>
        <el-button type="default" @click="resetPage">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button icon="Plus" type="primary" @click="addRole">新增职位</el-button>
    <el-table :cell-style="{textAlign: 'center'}" :data="roleList" :header-cell-style="{textAlign: 'center'}" border
              style="margin: 10px 0">
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="id" prop="id"></el-table-column>
      <el-table-column label="角色名称" prop="roleName" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="400px">
        <template #default="{row}">
          <el-button icon="Avatar" type="primary" @click="assignRole(row)">分配权限</el-button>
          <el-button icon="Edit" type="warning" @click="editCareer(row)">编辑</el-button>
          <el-button icon="Delete" type="danger" @click="deleteCareer(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="total"
        background
        layout="prev, pager, next, jumper, ->, total, sizes"
        @size-change="reqPage(1)"
        @current-change="reqPage(currentPage)"
    ></el-pagination>
  </el-card>
  <el-dialog v-model="isShow" title="添加职位">
    <template #default>
      <el-form ref="roleForm" :model="newRole" :rules="rules">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model.trim="newRole.roleName" placeholder="输入职位"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="saveRole">保存</el-button>
      <el-button type="text" @click="cancel">取消</el-button>
    </template>
  </el-dialog>
  <el-drawer v-model="isShowDrawer" title="分配权限">
    <template #default>
      <el-tree ref="tree" style="max-width: 600px" :data="menuList" show-checkbox node-key="id"
      default-expand-all :default-checked-keys="menuParams" :props="defaultProps">
      </el-tree>
    </template>
    <template #footer>
      <el-button @click="assignPermission" type="primary">保存</el-button>
      <el-button @click="cancel" type="text">取消</el-button>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: space-between;
}
</style>